import style from './index.module.scss'
import HeaderView from '@/component/Header'
import { Form, Button, Input, Toast } from 'antd-mobile'
import { NavLink } from 'react-router-dom'
import { UserRegister } from '@/api/loginRegister'
import { registerType } from '@/type/loginType'
import { useNavigate } from 'react-router-dom'

const Rgister = () => {
  const [form] = Form.useForm()
  const navigate = useNavigate()

  // 邮箱验证
  const checkEmail = (_: any, value: string) => {
    if(/^([a-zA-Z0-9])+@(([a-zA-Z0-9])+\.)+([a-zA-Z]{2,4})+$/g.test(value)) {
      return Promise.resolve()
    } else {
      return Promise.reject('请输入正确的邮箱格式')
    }
  }

  // 再次确认密码
  const checkPwd = (_: any, value: string) => {
    if(form.getFieldValue('password') !== value && value !== '') {
      return Promise.reject(new Error('两次输入的密码不一致'))
    }
    return Promise.resolve()
  }

  // 注册
  const onFinish = async(value: registerType) => {
    const res = await UserRegister({
      name: value.name, email: value.email, password: value.password, password_confirmation: value.password_confirmation
    })
    try {
      if(res?.status === 201) {
        Toast.show({icon: 'success', content: '注册成功', duration: 1500, maskClickable: false, afterClose: () => {
          navigate('/login')
        }})   
      }
    } catch (error) {
      console.log(error)
    }
    
  }

  return (
    <div className={style.headerBox}>
      {/* header--nvabar */}
      <HeaderView title='注册中心' backIcon={false}/>
       
      <div className={style.loginFormBox}>
        <Form layout='horizontal' form={form} onFinish={onFinish} footer={
          <>
            <NavLink to='/login' className={style.link}>立即登录</NavLink>
            <Button block type='submit' size='large' className={style.btn}>注册</Button>
          </>
        }>
          <Form.Item name='name' label='用户名' rules={[{ required: true, message: '用户名不能为空' }, {min: 3, max: 6, pattern: /^[a-zA-Z0-9]{3,6}$/, message: '用户名长度3-6位,数字和字母组成'}]}>
            <Input placeholder='请输入用户名'/>
          </Form.Item>
          <Form.Item name='password' label='密码' rules={[{ required: true, message: '密码不能为空' }]}>
            <Input type='password' placeholder='请输入密码'  autoComplete=''/>
          </Form.Item>
          <Form.Item name='password_confirmation' label='确认密码' validateTrigger="onBlur" rules={[{ required: true, message: '密码不能为空' }, {validator: checkPwd}]}>
            <Input type='password' placeholder='请确认密码' autoComplete=''/>
          </Form.Item>
          <Form.Item name='email' label='邮箱' rules={[{ required: true, message: ''}, {validator: checkEmail}]}>
            <Input placeholder='请输入邮箱' />
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
  
export default Rgister